package com.atguigu.test6;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author 路飞
 * @date 2024/4/6 15:08
 * @description 编程实现：线程A向队列Q中不停写入数据，线程B从队列Q中不停读取数据（只要Q中有数据）
 */
public class Test7 {
    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue<Computer> queue = new ArrayBlockingQueue<>(10);
        new Thread(new Producer(queue), "生产者线程").start();
        new Thread(new Consumer(queue), "消费者线程").start();
    }
}

class Producer implements Runnable{
    private ArrayBlockingQueue<Computer> queue;

    public Producer(ArrayBlockingQueue<Computer> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        int i = 0;
        for (; ; ) {
                i++;
                Computer computer = new Computer("华硕" + i, "灵蛇" + i);
            try {
                System.out.println(Thread.currentThread().getName() + "开始生产第" + i + "台电脑");
                queue.put(computer);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class Consumer implements Runnable {
    private ArrayBlockingQueue<Computer> queue;

    public Consumer(ArrayBlockingQueue<Computer> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        for (; ; ) {
            Computer computer;
            try {
                Thread.sleep(1000);
                computer = queue.take();
                System.out.println(Thread.currentThread().getName() + "开始消费" + computer);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class Computer {
    private String mainBoard;

    private String screen;

    public String getMainBoard() {
        return mainBoard;
    }

    public void setMainBoard(String mainBoard) {
        this.mainBoard = mainBoard;
    }

    public String getScreen() {
        return screen;
    }

    public void setScreen(String screen) {
        this.screen = screen;
    }

    public Computer(String mainBoard, String screen) {
        this.mainBoard = mainBoard;
        this.screen = screen;
    }

    public Computer() {
    }

    @Override
    public String toString() {
        return "Computer{" +
                "mainBoard='" + mainBoard + '\'' +
                ", screen='" + screen + '\'' +
                '}';
    }
}
